############# ########### ####### ##### ### ##
#
# Copyright (C) 2010 The Hursk Group, LLC
#
# This program is free software: you can redistribute it and/or modify 
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program (See file named COPYING).  If not, see 
# <http://www.gnu.org/licenses/>.
# 
############# ########### ####### ##### ### ##

#!/usr/bin/perl
use strict;
use File::Find;
use Cwd;
my $USAGE =
"USAGE:\n".
'perl nkf_recursive_decent_file_conversion.pl [nkf arguments, i.e. `-w8` for SHIFT-JIS] input.file_or_directory(use "." for PWD)';

unless (exists($ARGV[0])){warn $USAGE; exit}
my $nkf_args;
for (@ARGV){
    chomp;
    if ($_ =~ /^\-*(h|help)$/){warn $USAGE; exit}
    else {$nkf_args .= $_}
}
push my @directories_to_search, cwd();

find(\&wanted, @directories_to_search);

sub wanted {
    my $file = $File::Find::name;
    push my @cmd, ('nkf ', $nkf_args, $File::Find::name);
    my $cmd = "@cmd";
    next if (-d $File::Find::name or not -f $File::Find::name or $File::Find::name =~ /nkf_recursive.*/);
    my $output = `$cmd`;
    my $tempfile = $file.'.'."$$".'.'.'temp';
    `cp $file $tempfile`;
    `rm $file`;
    open FH, ">", $file;
    print FH $output; close FH;
    `rm $tempfile`;
    undef @cmd;
}


